requirejs.config({
    baseUrl: '../js/libs',
    paths: {
        jquery: 'jquery.min',
        jquery_route: 'jquery.route',
        bootstrap: "../../bootstrap-3.3.5/dist/js/bootstrap.min",
        menu : "../modules/index/menu",
        config: "../common/config",
        common:'../common/common',
        arttemplateUtil: '../js/common/arttemplate-util',
        ztree:'../plugins/ztree/js/jquery.ztree.core',
        ztreeCheck:'../plugins/ztree/js/jquery.ztree.excheck.min',
        ztreeHide:'../plugins/ztree/js/jquery.ztree.exhide',
        layer: '../plugins/layer/layer'
    },
    waitSeconds : 15,
	map : {
		'*' : {
			'css' : 'css'
		}
	},
    shim: { //引入没有使用requirejs模块写法的类库。backbone依赖underscore
    	'jquery': {
            exports: '$'
        },
        'bootstrap':['jquery'],
        'ztreeCheck':['css!../plugins/ztree/css/zTreeStyle/zTreeStyle.css'],
        'ztreeHide':['ztree']
    }
});
requirejs(['jquery', 'jquery_route','config', 'arttemplateUtil','menu','common','layer','ztree','ztreeCheck','ztreeHide'], 
		function($, jquery_route, config, arttemplateUtil,menu, common,layer,ztree,ztreeCheck,ztreeHide) {
	
	common.common_ajax_request('/api/seller/v1/queryGoodsForSpecialPriceConf',{},false,function(data,code,msg){
		for(var i=0; i< data.records.length; i++){
			var rec = data.records[i];
			jQuery("#rela_goods").append("<option value='"+rec.id+"'>"+rec.goods_name+"</option>");
		}
	}, null, "post");
	
	function loadConfAreaTree(goodsId){
		//根据商品id获取已配置价格的小区
		common.common_ajax_request('/api/seller/v1/getGoodsPriceRelaCommunity',{goods_id:goodsId},false,function(data,code,msg){
			loadTree(data);
		}, null, "post");
	}
	function loadSKUList(goodsId){
		common.common_ajax_request('/api/v1/querySKUList',{goodsId:goodsId},false,function(data,code,msg){
			var arr = [];//初始化小区sku list
			var oarr = [];//初始化老用户sku list
			for(var i=0; i<data.length; i++){
				var record = data[i];
				//console.log(record);
				arr.push("<li>");
				arr.push("<div class=\"w150\">"+record.delivery_name+"</div>");
				arr.push("<div class=\"w130\">"+record.delivery_time+"</div>");
				arr.push("<div class=\"w130\">"+record.goods_price_before+"</div>");
				arr.push("<div class=\"w130\"><input type=\"text\" name=\"goods_price_act\" class=\"form-control\" id-val='"+record.id+"' value=''></div>");
                arr.push("</li>");
                //
                oarr.push("<li>");
                oarr.push("<div class=\"w150\">"+record.delivery_name+"</div>");
                oarr.push("<div class=\"w130\">"+record.delivery_time+"</div>");
                oarr.push("<div class=\"w130\">"+record.goods_price_before+"</div>");
                oarr.push("<div class=\"w130\"><input type=\"text\" name=\"goods_price_old_user\" class=\"form-control\" id-val='"+record.id+"' value='"+record.goods_price_old_user+"'></div>");
                oarr.push("</li>");
			}
			$('#commPriceConf').html(arr.join(''));
			$('#oldUserPriceConf').html(oarr.join(''));
		}, null, "post");
	}
	$("#rela_goods").change(function(){
		if($(this).val() != 0){
			common.loading();
			loadConfAreaTree($(this).val());
			loadSKUList($(this).val());
		}
	});
	
	$('#setPriceBtn').click(function(){
		if($("#rela_goods").val()==0){
			layer.alert("请先选择商品！");
			return;
		}
		var checkedNodes = area_tree.getCheckedNodes(true);
		var areaIdsArr = [];
		for(var i=0;i<checkedNodes.length;i++){
    		if(checkedNodes[i].isCommunity == 1){//如果是社区
    			areaIdsArr.push(checkedNodes[i].id);
    		}
		}
		if(areaIdsArr.length <= 0){
			layer.alert("至少选择一个小区");
			return;
		}
		$('#setPrice').modal('show');
	});
	
	var loadTree = function(confAreas){
		//common.loading();
		common.common_ajax_request('/api/v1/area_tree',{},false,function(data,code,msg){
			///console.debug(JSON.stringify(data));
			for(var t in data){
				if(data[t].isCommunity == 1){
					if(confAreas.indexOf(data[t].id) == -1){
						data[t].name += "&nbsp;&nbsp; <i style='color:gray;'>未配置</i>";
					}else{
						data[t].name += "&nbsp;&nbsp; <b style='color:green;'>已配置</b>";
					}
				}
			}
			ztree_data = data;
			var setting = {check: {enable: true},data: {simpleData: {enable: true}},view: { showIcon: true, selectedMulti: true, nameIsHTML: true, fontCss: setFontCss_ztree }};
			area_tree=$.fn.zTree.init($("#ztreeShow"), setting, data);
			layer.closeAll('loading');
		}, null, "post");
	};
	var area_tree,ztree_data;
    /**
     * 搜索树，高亮显示并展示【模糊匹配搜索条件的节点s】
     * @param treeId
     * @param searchCondition     搜索条件
     * @param flag                  需要高亮显示的节点标识
     */
    function searchByFlag_ztree(treeId, searchCondition){
        //<2>.得到模糊匹配搜索条件的节点数组集合
        var highlightNodes = new Array();
        if (searchCondition != "") {
            var treeObj = $.fn.zTree.getZTreeObj(treeId);
            highlightNodes = treeObj.getNodesByParamFuzzy("name", searchCondition, null);
        }
        //<3>.高亮显示并展示【指定节点s】
        highlightAndExpand_ztree(treeId, highlightNodes);
    }
     
    /**
     * 高亮显示并展示【指定节点s】
     * @param treeId
     * @param highlightNodes 需要高亮显示的节点数组
     */
    function highlightAndExpand_ztree(treeId, highlightNodes){
        var treeObj = $.fn.zTree.getZTreeObj(treeId);
        //<1>. 先把全部节点更新为普通样式
        var treeNodes = treeObj.transformToArray(treeObj.getNodes());
        for (var i = 0; i < treeNodes.length; i++) {
            treeNodes[i].highlight = false;
            treeObj.updateNode(treeNodes[i]);
        }
        //<2>.收起树, 只展开根节点下的一级节点
        //close_ztree(treeId);
        //<3>.把指定节点的样式更新为高亮显示，并展开
        //alert(highlightNodes.length);
        if (highlightNodes != null) {
            for (var i = 0; i < highlightNodes.length; i++) {
            	searchResultIds.push(highlightNodes[i].tId);
                {
                    //高亮显示节点，并展开
                    highlightNodes[i].highlight = true;
                    treeObj.updateNode(highlightNodes[i]);
                    //高亮显示节点的父节点的父节点....直到根节点，并展示
                    var parentNode = highlightNodes[i].getParentNode();
                    var parentNodes = getParentNodes_ztree(parentNode);
                    treeObj.expandNode(parentNodes, true, false, true);
                    treeObj.expandNode(parentNode, true, false, true);
                }
            }
            //过滤不在搜索条件里面的节点
            var nodes = treeObj.transformToArray(treeObj.getNodes());
            var nodeLength = nodes.length;
            for (var i = 0; i < nodeLength; i++) {
            	if(!nodes[i].checked && !nodes[i].isParent){
            		if(searchResultIds.indexOf(nodes[i].tId)==-1){
            			treeObj.hideNode(nodes[i]);
            		}
            	}
            }
        }
    }
     
    /**
     * 递归得到指定节点的父节点的父节点....直到根节点
     */
    function getParentNodes_ztree(node){
        if (node != null) {
            var parentNode = node.getParentNode();
            return getParentNodes_ztree(parentNode);
        } else {
            return node;
        }
    }
     
    /**
     * 设置树节点字体样式
     */
    function setFontCss_ztree(treeId, treeNode) {
        if (treeNode.id == 0) {
            //根节点
            return {color:"#333", "font-weight":"bold"};
        } else if (treeNode.isParent == false){
            //叶子节点
            return (!!treeNode.highlight) ? {color:"#ff0000", "font-weight":"bold"} : {color:"#660099", "font-weight":"normal"};
        } else {
            //父节点
            return (!!treeNode.highlight) ? {color:"#ff0000", "font-weight":"bold"} : {color:"#333", "font-weight":"normal"};
        }
    }
    
    function initTreeNodes(){
    	var treeObj = $.fn.zTree.getZTreeObj('ztreeShow');
        //<1>. 先把全部节点更新为普通样式
        var treeNodes = treeObj.transformToArray(treeObj.getNodes());
        for (var i = 0; i < treeNodes.length; i++) {
        	if(treeNodes[i].isHidden){
        		treeObj.showNode(treeNodes[i]);
        	}
            treeNodes[i].highlight = false;
            treeObj.updateNode(treeNodes[i]);
        }
    }
	
	
	var searchResultIds = [];
	var curr_node_index = 0;
	var cur_offset_top = 0;
	$("#search_node_btn").click(function(){
		if($("#rela_goods").val() == '' || $("#rela_goods").val() == 0){
			layer.msg("请先选择商品！");
			return;
		}
		common.loading();
		window.setTimeout(function(){
			curr_node_index = 0;
			searchResultIds=[];
			cur_offset_top = 0;
			
			initTreeNodes();
			var searchText = $("#search_node_text").val();
	    	if(searchText == ''){
	    		//layer.msg("查询条件不能为空");
	    	}else{
	    		searchByFlag_ztree('ztreeShow', searchText);
	    		$("#searbox").scrollTop(0);
	    		if(searchResultIds.length > 0){
	    			cur_offset_top = $("#"+searchResultIds[curr_node_index]+"_a").offset().top - $("#searbox").offset().top;
	    			$("#searbox").animate({scrollTop:cur_offset_top},1000);//1000是ms,也可以用slow代替
	    		}else{
	    			layer.msg("没有查询结果");
	    		}
	    	}
	    	layer.closeAll('loading');
		}, 10);
	});
	
	//单选按钮点击切换隐藏
	$('input:radio[name="active-price"]').each(function(i){
		$(this).click(function(){
			if(i==0){
				$(".nomalprice").show();
				$(".oldprice").hide();
				$(".submit_div").hide();
				$("#rela_price_conf_lab").html("选择关联小区价格：");
			}else{
				$(".nomalprice").hide();
				$(".oldprice").show();
				$(".submit_div").show();
				$("#rela_price_conf_lab").html("价格配置：");
			}
		});
	});
	
	var _regnumber= /^0\.[1-9]$|^0\.[1-9][0-9]$|^0\.[0-9][1-9]$|^([1-9][0-9]{0,4})(\.[0-9]{1,2})?$/;
	$("#comm_price_submit_btn").click(function(){
		var param = [];
		var flag = true;
		$("#commPriceConf").find('input').each(function(_index2,_data2){
			var _val = $(this).val();
			if(!_regnumber.test(_val)){
				layer.msg("活动价格必须是数字且在0.01-99999.99之间");
				$(this).focus();
				flag = false;
				return flag;
			}
			var _skuId = $(this).attr("id-val");
			param.push({"name":"specialPriceListVo["+_index2+"].special_price","value":_val});
			param.push({"name":"specialPriceListVo["+_index2+"].goods_sku_id","value":_skuId});
		});
		if(!flag){
			return;
		}
		common.loading();
		var goods_id = $("#rela_goods").val();
		var checkedNodes = area_tree.getCheckedNodes(true);
		
		//var j = 0;
		var areaArr = [];
		for(var i=0;i<checkedNodes.length;i++){
			var area = {};
    		if(checkedNodes[i].isCommunity == 1){//如果是社区
    			area.area_id=checkedNodes[i].id;
    			if(checkedNodes[i].name.indexOf("&")>-1){
    				area.area_name = checkedNodes[i].name.split("&")[0];
    			}else{
    				area.area_name = checkedNodes[i].name;
    			}
    			areaArr.push(area);
    		}
		}
		param.push({"name":"specialCommunityJson","value":JSON.stringify(areaArr)});
		param.push({"name":"goodsId","value":goods_id});
		param.push({"name":"special_type","value":2});
		//console.info(param);
		common.common_ajax_request('/api/seller/v1/saveSpecialPrice',param,false,function(data,code,msg){
			if(code==200 && msg.businessCode==0){
        		window.layer.alert('保存成功!', {
      			  icon: 1,closeBtn:false
      			}, function(){
      				//
      				loadConfAreaTree(goods_id);
      				loadSKUList(goods_id);
      				$('#setPrice').modal('hide');
      				layer.closeAll();
      			}); 
			}else{
				layer.closeAll();
				layer.alert(msg.businessNote);
			}
		}, null, "post");
	});
	//保存老用户价格
	$("#save_olduser_price_btn").click(function(){
		var param = [];
		var flag = true;
		$("#oldUserPriceConf").find('input').each(function(_index2,_data2){
			var _val = $(this).val();
			if(!_regnumber.test(_val)){
				layer.msg("活动价格必须是数字且在0.01-99999.99之间");
				$(this).focus();
				flag = false;
				return flag;
			}
			var _skuId = $(this).attr("id-val");
			param.push({"name":"specialPriceListVo["+_index2+"].special_price","value":_val});
			param.push({"name":"specialPriceListVo["+_index2+"].goods_sku_id","value":_skuId});
		});
		if(!flag){
			return;
		}
		common.loading();
		var goods_id = $("#rela_goods").val();
		
		param.push({"name":"specialCommunityListVo[0].area_id","value":0});
		param.push({"name":"specialCommunityListVo[0].area_name","value":""});
		param.push({"name":"goodsId","value":goods_id});
		param.push({"name":"special_type","value":1});
		//console.info(param);
		common.common_ajax_request('/api/seller/v1/saveSpecialPrice',param,false,function(data,code,msg){
			if(code==200 && msg.businessCode==0){
				layer.closeAll();
        		window.layer.alert('保存成功!');
        		//loadSKUList(goods_id);
			}else{
				layer.closeAll();
				layer.alert(msg.businessNote);
			}
		}, null, "post");
	});
	
	$("#delPriceBtn").click(function(){
		var param = [];
		var goods_id = $("#rela_goods").val();
		if(goods_id == '' || goods_id == 0){
			layer.msg("请先选择商品！");
			return;
		}
		param.push({"name":"goods_id","value":goods_id});
		
		var checkedNodes = area_tree.getCheckedNodes(true);
		if(checkedNodes.length == 0){
			layer.msg("至少选择一个社区！");
			return;
		}
		
		var areaIdsJson= [];
		for(var i=0;i<checkedNodes.length;i++){
    		if(checkedNodes[i].isCommunity == 1){//如果是社区
    			areaIdsJson.push(checkedNodes[i].id);
    		}
		}
		param.push({"name":"area_ids_arr","value":areaIdsJson});
		
		common.loading();
		layer.confirm('确定删除吗？', {
			  btn: ['确定','取消']
		}, function(){
			//console.info(param);
			common.common_ajax_request('/api/seller/v1/deleteCommunityPrice',param,false,function(data,code,msg){
				if(code==200 && msg.businessCode==0){
	        		window.layer.alert('保存成功!', {
	      			  icon: 1,closeBtn:false
	      			}, function(){
	      				//
	      				loadConfAreaTree(goods_id);
	      				layer.closeAll();
	      			}); 
				}else{
					layer.closeAll();
					layer.alert(msg.businessNote);
					
				}
			}, null, "post");
		}, function(){});
	});
	$("#reset_btn").click(function(){
		$("#commPriceConf").find('input').each(function(_index2,_data2){
			$(this).val("");
		});
	});
	$("#ret_btn").click(function(){
		$("#oldUserPriceConf").find('input').each(function(_index2,_data2){
			$(this).val("");
		});
	});
});